package com.lw.sbdemo2.web.wxmin;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.lw.sbdemo2.common.wxmin.WxMaConfiguration;
import com.lw.sbdemo2.service.TkUserInfoService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 微信小程序用户接口
 */
@RestController
@RequestMapping("/wxmin/user/{appId}")
@Slf4j
public class WxMaUserController {

    @Autowired
    private TkUserInfoService tkUserInfoService;

    /**
     * 小程序登录接口
     * 根据临时码获取令牌
     *
     * @param code
     * @return
     * @throws Exception
     */
    @GetMapping("login")
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> login(@PathVariable String appId, @RequestParam String code) throws Exception {

        Map<String, Object> dataMap = new HashMap<>(16);

        try {
            final WxMaService wxService = WxMaConfiguration.getMaService(appId);
            log.info("根据临时码获取令牌，code={}", code);
            WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(code);
            dataMap.put("user", tkUserInfoService.userLogin(session, appId));
            return dataMap;
        } catch (WxErrorException e) {
            log.error("调用小程序登录接口失败", e);
            return null;
        }
    }

}
